﻿#region Copyrights Notice
//©2009 Microsoft Corporation.  All rights reserved.
//This portal design is based on the design and some code from DropThings.com which is also licensed under an MS-PL license.
#endregion


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.InformationSecurity.CISF.Portal.Business;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.UserControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.TasksService;
using FACTORY = Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;



namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb
{


    public partial class _Default : System.Web.UI.Page
    {
        
        private const int NoOfWidgetsInWidgetManager = 12;

        //username from context
        //todo change from AuthZservice
        //Context.User.Identity.Name
        string _UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\')[1].ToString();
        
        private int AddMoretoThisPageWidgetListIndex
        {
            get { object val = ViewState["AddMoretoThisPageWidgetListIndex"]; if (val == null) return 0; else return (int)val; }
            set { ViewState["AddMoretoThisPageWidgetListIndex"] = value; }
        }

        private List<SingleWeblet> ControlList
        {
            get
            {
                List<SingleWeblet> _widgets = Cache["Widgets"] as List<SingleWeblet>;
                if (null == _widgets)
                {
                    _widgets = new PortalFacade(_UserName).GetWidgetList();
                    Cache["Widgets"] = _widgets;
                }

                return _widgets;
            }
        }
        private UserWidgetSetup _UserWidgetSetup
        {
            get { return Context.Items[typeof(UserWidgetSetup)] as UserWidgetSetup; }
            set { Context.Items[typeof(UserWidgetSetup)] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _UserName = Context.User.Identity.Name.Split('\\')[1].ToString();
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            this.LoadUserWidgetSetup();

            this.ShowAddMoreWidgetsPanel();

            // First visit, non postback            
            this.RenderWidgets(!ScriptManager.GetCurrent(Page).IsInAsyncPostBack);
        }
        private void LoadUserWidgetSetup()
        {
            //Ideally this has to be stored and read from User Profile which will be performant.
            //Am checking this from Database...

            var PortalFacade = new PortalFacade(_UserName);

            if (!PortalFacade.IsUserRegistered())
            {
                _UserWidgetSetup = PortalFacade.NewUserVisit();
            }
            else
            {
                _UserWidgetSetup = PortalFacade.LoadUserSetup();
            }
        }
        private void RenderWidgets(bool isWidgetFirstLoad)
        {
            var setup = _UserWidgetSetup;
             
            Panel[] columnPanels = WidgetColumnPanelsLayout.GetPanels();
            foreach (Panel panel in columnPanels)
            {
                List<ContainerUserControl> widgets = panel.Controls.OfType<ContainerUserControl>().ToList();
                foreach (var widget in widgets) panel.Controls.Remove(widget);
            }

            foreach (RealWeblet instance in setup.RealWeblets)
            {
            
                var panel = columnPanels[instance.TableColPos];
                ContainerUserControl widget = FACTORY.WebletControlFactory2.CreateControlHost(this) as ContainerUserControl;
                widget.ID = "WidgetHost" + instance.WidgetInstanceId.ToString();
                widget.FirstTime = isWidgetFirstLoad;
                widget.ac.RealWebletControl = instance;
                widget.OnControlDelete += new Action<RealWeblet>(widget_Deleted);
                try
                {
                    panel.Controls.Add(widget);
                }
            catch { }
             
            }

        }
        protected void AddMoreWidgets_Click(object sender, EventArgs e)
        {
            this.ResetHomePagePanel.Visible = false;
            this.AddMoreToThisPagePanel.Visible = !this.AddMoreToThisPagePanel.Visible;

            this.ShowAddMoreWidgetsPanel();
        }
        private void ShowAddMoreWidgetsPanel()
        {
            if (this.AddMoreToThisPagePanel.Visible)
            {
                var itemsToShow = ControlList.Skip(AddMoretoThisPageWidgetListIndex * NoOfWidgetsInWidgetManager).Take(NoOfWidgetsInWidgetManager);
                this.WidgetDataList.DataSource = itemsToShow;
                this.WidgetDataList.DataBind();

                this.WidgetListPreviousLinkButton.Visible = AddMoretoThisPageWidgetListIndex > 0;
                this.WidgetListNextButton.Visible = AddMoretoThisPageWidgetListIndex * NoOfWidgetsInWidgetManager + NoOfWidgetsInWidgetManager < ControlList.Count;
            }
        }
        protected void ResetWidgets_Click(object sender, EventArgs e)
        {
            this.AddMoreToThisPagePanel.Visible = false;
            this.ResetHomePagePanel.Visible = !this.ResetHomePagePanel.Visible;

        }
        protected void ResetHomePageSave_Click(object sender, EventArgs e)
        {
            this.ResetHomePagePanel.Visible = false;

            //Start over...
            var PortalFacade = new PortalFacade(_UserName);

            _UserWidgetSetup = PortalFacade.ResetUserSetup();

            this.RenderWidgets(!ScriptManager.GetCurrent(Page).IsInAsyncPostBack);
            this.RefreshAllWidgetColumns();
        }
        protected void ResetHomePageCancel_Click(object sender, EventArgs e)
        {
            this.ResetHomePagePanel.Visible = false;
            //do nothing...
        }

        protected void AddWidgetsSave_Click(object sender, EventArgs e)
        {
            this.AddMoreToThisPagePanel.Visible = false;

            //Get the selected widget list.
            UserWidgetSetup _newSetup = new UserWidgetSetup();
            //find datalist.
            IEnumerable<DataList> DataList = this.AddMoreToThisPagePanel.Controls.OfType<DataList>();

            DataListItemCollection items = DataList.OfType<DataList>().Single().Items;
            foreach (DataListItem i in items)
            {
                CheckBox c = i.Controls.OfType<CheckBox>().Single();

                if (c.Checked == true)
                {
                    Int32 id = Int32.Parse(c.Attributes["WidgetId"]);

                    //Find widget in the widget list.
                    SingleWeblet w = ControlList.Find(w1 => (w1.WidgetId == id));
                    //Construct WigetInstnace.
                    RealWeblet wi = new RealWeblet(w);
                    _newSetup.RealWeblets.Add(wi);
                }
            }

            PortalFacade PortalFacade = new PortalFacade(_UserName);
            _UserWidgetSetup = PortalFacade.UpdateUserSetup(_UserWidgetSetup, _newSetup);

            this.RenderWidgets(!ScriptManager.GetCurrent(Page).IsInAsyncPostBack);
            this.RefreshAllWidgetColumns();

        }
        protected void WidgetDataList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                SingleWeblet widget = e.Item.DataItem as SingleWeblet;

                CheckBox w = e.Item.Controls.OfType<CheckBox>().Single();

                w.Text = " " + widget.Name;
                w.ID = "AddWidget_" + widget.WidgetId.ToString();
                w.Attributes.Add("WidgetId", widget.WidgetId.ToString());
                w.Checked = IsWidgetSelected(widget.Name);
            }
        }
        private bool IsWidgetSelected(string widgetTitle)
        {
            var setup = _UserWidgetSetup;

            foreach (RealWeblet instance in setup.RealWeblets)
            {
                if (instance.Caption.Equals(widgetTitle))
                    return true;
            }
            return false;
        }
        protected void AddWidgetsCancel_Click(object sender, EventArgs e)
        {
            this.AddMoreToThisPagePanel.Visible = false;
        }



        protected void WidgetListPreviousLinkButton_Click(object sender, EventArgs e)
        {
            if (0 == this.AddMoretoThisPageWidgetListIndex)
                return;

            this.AddMoretoThisPageWidgetListIndex--;

            this.ShowAddMoreWidgetsPanel();
        }
        protected void WidgetListNextButton_Click(object sender, EventArgs e)
        {
            this.AddMoretoThisPageWidgetListIndex++;
            this.ShowAddMoreWidgetsPanel();
        }
        private void RefreshAllWidgetColumns()
        {
            this.UpdateWebletPanel(0);
            this.UpdateWebletPanel(1);
            this.UpdateWebletPanel(2);
        }

        private void UpdateWebletPanel(int columnNo)
        {
        
            this.WidgetColumnPanelsLayout.UpdateWebletPanel(columnNo);



        }

        void widget_Deleted(RealWeblet wi)
        {
            _UserWidgetSetup = new PortalFacade(_UserName).GetUserSetup();
            this.RenderWidgets(!ScriptManager.GetCurrent(Page).IsInAsyncPostBack);
            this.RefreshAllWidgetColumns();
        }
    }
}